package main

import (
	amqp "github.com/rabbitmq/amqp091-go"
	"log"
	"zhongxc.cc/go-common/errs"
	"zhongxc.cc/go-common/mq"
)

func Receive() {
	// 1. 建立链接
	conn := mq.NewRabbitMqConnection()
	defer func(conn *amqp.Connection) {
		_ = conn.Close()
	}(conn)

	// 2. 获取channel
	channel, err := conn.Channel()
	errs.FailOnError(err, "Failed to open a channel")
	defer func(channel *amqp.Channel) {
		_ = channel.Close()
	}(channel)

	queue, err := channel.QueueDeclare(
		"hello",
		false,
		false,
		false,
		false,
		nil,
	)
	errs.FailOnError(err, "Failed to declare a queue")

	consume, err := channel.Consume(
		queue.Name,
		"",
		true,
		false,
		false,
		false,
		nil,
	)

	forever := make(chan bool)
	go func() {
		for d := range consume {
			log.Printf("Received a message: %s\n", d.Body)
		}
	}()
	log.Printf("[*] Waiting for messages. To exit press CTRL+C")
	<-forever
}

func main() {
	Receive()
}
